package com.yiper.service.impl;

import com.yiper.entity.User;
import com.yiper.entity.UserRole;
import com.yiper.mapper.UserMapper;
import com.yiper.mapper.UserRoleMapper;
import com.yiper.service.UserService;
import com.yiper.util.ResponseUtil;
import com.yiper.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Service实现类
 *
 * @author yiper
 * @since 2018年7月5日 上午11:54:24
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public User selectByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public int register(User user) {
        int a = userMapper.insert(user);
        return a;
    }

    /**
     * 根据搜索条件查询所有用户
     *
     * @param user
     * @return
     */
    @Override
    public List<User> selectUsers(User user) {
        return userMapper.selectUsers(user);
    }

    /**
     * 根据id批量删除用户
     *
     * @param userIdsList
     * @param status
     * @return
     */
    @Override
    public int updateStatusBatch(List<String> userIdsList, Integer status) {
        Map<String,Object> params = new HashMap<String,Object>(2);
        params.put("userIds",userIdsList);
        params.put("status",status);
        return userMapper.updateStatusBatch(params);
    }

    /**
     * 根据用户id查询用户详情
     *
     * @param userId
     * @return user
     */
    @Override
    public User selectByUserId(String userId) {
        return userMapper.selectByUserId(userId);
    }

    /**
     * 根据用户id更新用户信息
     *
     * @param user
     * @return int
     */
    @Override
    public int updateByUserId(User user) {
        return userMapper.updateByUserId(user);
    }

    /**
     * 给用户分配角色
     *
     * @param userId
     * @param roleIdsList
     * @return
     */
    @Override
    public ResponseVo addAssignRole(String userId, List<String> roleIdsList) {
        try{
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRoleMapper.delete(userRole);
            for(String roleId :roleIdsList){
                if(roleId != ""){
                    userRole.setRoleId(roleId);
                    userRoleMapper.insert(userRole);
                }
            }
            return ResponseUtil.success("角色分配成功");
        }catch(Exception e){
            return ResponseUtil.error("分配角色失败");
        }
    }


    /**
     * 修改用户信息
     *
     * @param newUser
     * @return
     */
    @Override
    public int updateUserByPrimaryKey(User newUser) {
        return userMapper.updateByPrimaryKey(newUser);
    }


}
